
import { Collapse } from 'antd-mobile'
import './index.scss'
import DayDetail from '../DayDetail'
import { useMemo, useState } from 'react'
import dayjs from 'dayjs'
import _ from 'loadsh'

const Panel = ({list,date})=> {
    const dayResult = useMemo(()=> {
        // 收入/支出/结余
        const pay = (list && list.filter(d => d.type === 'pay').reduce((a,c)=> a+c.money,0)) || 0
        const income = (list && list.filter(d => d.type === 'income').reduce((a,c)=> a+c.money,0))|| 0
        return {
            pay,
            income,
            total:  income - pay
        }
    },[list])
    return (
        <>
            <div className="myDate">
                {date}
            </div>
            <div className="myPanel">
                <div className="panelItem">
                    <span className="payTitle">支出</span>
                    <span className="money">{dayResult.pay.toFixed(2)}</span>
                </div>
                <div className="panelItem">
                    <span className="incomeTitle">收入</span>
                    <span className="money">{dayResult.income.toFixed(2)}</span>
                </div>
                <div className="panelItem">
                    <span className="totalTitle">结余</span>
                    <span className="money totalMoney">{dayResult.total.toFixed(2)}</span>
                </div>
            </div>
        </>
    )
}
const DayBill = ({list}) => {
    // 按日期分组数据
    const dayGroup = useMemo(()=> {
        const groupData = _.groupBy(list,(item)=> dayjs(item.date).format('YYYY-MM-DD'))
        const dayKeys = Object.keys(groupData)
        return {
            groupData,
            dayKeys
        }
    },[list])
    console.log("dayGroup:",dayGroup)

    const [activeKey,setActiveKey] = useState('')
    const collapseOpen = (activeKey) => {
        setActiveKey(activeKey)
    }

    return (
        <div className="dayBill">
            <Collapse defaultActiveKey={[activeKey]} onChange={collapseOpen}>
                {dayGroup.dayKeys.map(key => (
                    <Collapse.Panel key={key} title={<Panel date={key} list={dayGroup.groupData[key]}/>}>
                        {
                           dayGroup.groupData[key] && dayGroup.groupData[key].map(item => (
                                <DayDetail key={item.id} data={item} />
                           )) 
                        }
                    </Collapse.Panel>
                ))}
            </Collapse>
        </div>
    )
}

export default DayBill